package com.han.demo.springbootmodulelistener;

import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * @author hanjl
 * @Description 文件工具类：文件读写，同时提供进度条提示的功能供使用者可选开启
 * @ClassName MyFileUtil
 * @createTime 2021/11/17 18:15
 */
@Slf4j
public class MyFileUtil {

    /**
     * 文件读写方法，事件的发起者
     */
    public static void doWriteFile(String inPath, String putPath) throws IOException {
        //获取输入流
        FileInputStream fis = new FileInputStream(inPath);
        BufferedInputStream bis = new BufferedInputStream(fis);
        //定义输出流
        FileOutputStream fos = new FileOutputStream(putPath);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        //定义读取缓存区
        int PAGE_SIZE = 100;
        byte[] bytes = new byte[PAGE_SIZE];
        //定义文件大小和读取量
        int fileSize = fis.available();
        int readSize = 0;
        while(true){
            //如果不足一缓存冲区数据，全部读出
            if(fileSize <= PAGE_SIZE){
                byte[] b = new byte[fileSize];
                bis.read(b);
                bos.write(b);
                break;
            }else if(fileSize < readSize + PAGE_SIZE){
                //如果是最后一个读取
                byte[] b = new byte[fileSize-readSize];
                bis.read(b);
                bos.write(b);
                break;
            }else{ //中间分页读取
                bis.read(bytes);
                bos.write(bytes);
                readSize += PAGE_SIZE;
            }

            //事件管理器在每次读写时发布这个事件，由各个监听器监听，对此感兴趣的监听器会触发
            log.info("文件读写事件触发，事件管理器发布事件等待监听...");
            MyApplicationListenerManager.pushEvent(new MyFileEvent(fileSize,readSize));

        }
        bos.flush();
        fis.close();
        fos.close();
    }
    //测试文件读取
    public static void main(String[] args) throws IOException {

        //添加该事件监听器并将这个事件发布，获取fileSize和readSize
        log.info("事件管理器注册所有监听器-start");
        MyApplicationListenerManager.addListener(new MyFileListener());
        MyApplicationListenerManager.addListener(new BListener());
        log.info("事件管理器注册所有监听器-end");

        //读写操作
        MyFileUtil.doWriteFile("C:\\Users\\hanjl\\Desktop\\密码.txt",
                "C:\\Users\\hanjl\\Desktop\\密码99999.txt");
    }


}
